import 'package:flutter/material.dart';
import 'package:flutter_demo/model/post.dart';

class DataTableDemo extends StatefulWidget {
  const DataTableDemo({super.key});

  @override
  State<DataTableDemo> createState() => _DataTableDemoState();
}

class _DataTableDemoState extends State<DataTableDemo> {
  int _sortColumnIndex = 0;
  bool _sortAscending = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('DataTableDemo'),
        elevation: 0.0,
      ),
      body: Container(
        padding: EdgeInsets.all(16.0),
        child: ListView(
          children: [
            DataTable(
                sortColumnIndex: _sortColumnIndex, //第几栏 做箭头符号
                sortAscending: _sortAscending,
                onSelectAll: (value) { //点击全选
                    print('selectAll $value');
                }, //true升序 false降序
                columns: [
                  DataColumn(
                      label: Container(
                        width: 30.0,
                        child: Text('Title'),
                      ),
                      onSort: (int index, bool ascending) {
                        setState(() {
                          _sortColumnIndex = index;
                          _sortAscending = ascending;

                          posts.sort((a, b) {
                            if (!ascending) {
                              final c = a;
                              a = b;
                              b = c;
                            }
                            return a.title!.length.compareTo(b.title!.length);
                          });
                        });
                      }),
                  DataColumn(label: Text('Author')),
                  DataColumn(label: Text('Image')),
                ],
                rows: posts.map((post) {
                  return DataRow(
                      selected: post.selected,
                      onSelectChanged: (value) {
                        setState(() {
                          if (post.selected != value) {
                            post.selected = value!;
                          }
                        });
                      },
                      cells: [
                        DataCell(Text(post.title!)),
                        DataCell(Text(post.author!)),
                        DataCell(Image.network(post.imageUrl!)),
                      ]);
                }).toList())
          ],
        ),
      ),
    );
  }
}
